import { useState, useEffect } from 'react';
import * as echarts from 'echarts';
import emitter from '#/utils/events';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/title';

const useCharts = (chartRef, config) => {
  let chartInstance = null;
  const [Item, setItem] = useState({});
  const [HideItem, setHideItem] = useState(false);

  const renderChart = () => {
    const renderedInstance = echarts.getInstanceByDom(chartRef.current);
    if (renderedInstance) {
      chartInstance = renderedInstance;
    } else {
      chartInstance = echarts.init(chartRef.current);
    }
    chartInstance.setOption(config);
    chartInstance.on('mouseover', function (params) {
      setHideItem(false);
      setItem(params);
      chartInstance.dispatchAction({
        type: !Number.isNaN(params.value) ? 'highlight' : 'downplay',
        name: params.name,
      });
    });
    chartInstance.on('mouseout', function (params) {
      chartInstance.dispatchAction({
        type: 'downplay',
        name: params.name,
      });
    });
    chartInstance.on('globalout', function () {
      setHideItem(true);
    });
    chartInstance.resize();
  };

  useEffect(() => {
    chartRef.current && renderChart();
  }, [config]);

  useEffect(
    () => () => {
      chartInstance && chartInstance.dispose();
    },
    [],
  );

  const handleMapDispatch = (flag) => {
    chartInstance &&
      chartInstance.on('mouseover', function (params) {
        chartInstance.dispatchAction({
          type: flag ? 'highlight' : 'downplay',
          name: params.name,
        });
      });
  };

  const handleCartsResize = () => {
    chartInstance && chartInstance.resize();
  };

  useEffect(() => {
    window.addEventListener('resize', () => {
      if (!chartRef) {
        window.removeEventListener('resize', handleCartsResize);
        return;
      }
      handleCartsResize();
    });
  }, [config]);

  useEffect(() => {
    emitter.addListener('onChangeMnue', _onHandleResize);
    return () => {
      emitter.removeListener('onChangeMnue', _onHandleResize);
    };
  }, [config]);

  const _onHandleResize = () => {
    setTimeout(() => {
      handleCartsResize();
    }, 500);
  };

  return {
    chartInstance,
    Item,
    HideItem,
    handleCartsResize,
    handleMapDispatch,
  };
};

export default useCharts;
